/*
 * chinanet 接口总文件
 * by wzdxx1314@163.com
 * 2021-6-1
 * */

const axios = require('axios');
const qs = require('qs')
import autherConfig from "../../config/autherConfig";
import {
    Message
} from 'element-ui'
import router from "../router";

const instance = axios.create({
    baseURL: '/api',
    // baseURL: '/apicz/',
    timeout: 50000,
});
let goLogin = false

/*
 *
 * 请求的预处理 by wzd
 * */
instance.interceptors.request.use((config) => {
    if (config.url === 'api/system/login') {
        config.headers['biyiCaptchaKey'] = window.biyiCaptchaKey;
        config.headers['biyiCaptcha'] = JSON.stringify({
            code: window.biyiCaptcha
        });
        config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    }
    config.headers['Accept'] = '';
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    config.headers['Authorization'] =  sessionStorage.getItem('token')
    return config;
}, (error) => {
    return Promise.reject(error);
});

/*
 *
 * 返回的预处理 by wzd
 * */
instance.interceptors.response.use(function (response) {
    // Do something with response data
    return response.data;
}, function (error) {
    return Promise.reject(error);
});
let messageInstance = null; // 默认 Message 未打开
function fetch(ourl, params = {}, methods = 'post') {
    return new Promise((resolve, reject) => {
        let url = ourl;
        if (methods == 'get' && qs.stringify(params)) {
            url = ourl + '?' + qs.stringify(params);
        }
        instance[methods](url, params).then(res => {
            if (ourl == 'api/catpcha/digitalCaptcha' || ourl == 'api/system/login' || ourl == 'api/system/loginSSO' || ourl == 'api/admin/getLoginStatus') {
                resolve(res)
            } else {
                if (res.code == 200) {
                    resolve(res)
                }else if(res.code == 501 || res.code == 401){
                   if(goLogin == false){
                       let localHref = encodeURIComponent(`${window.location.origin}/#/singleLogin`)
                       let href = `${autherConfig.ip}esc-sso/oauth2.0/authorize?client_id=${autherConfig.ip_id}&response_type=code&redirect_uri=${localHref}`
                       window.open(href,'_self')
                       goLogin = true
                   }
                    reject(res)
                } else {
                    Message({
                        type: 'error',
                        message: res.message,
                    });
                    reject(res)
                }
            }


        }).catch((err) => {
            if (err.response?.data?.status === 401) {
                // if (messageInstance) {
                //   messageInstance.close() //关闭
                // }
                const resetMessage = (options) => {
                    if (messageInstance) messageInstance.close() // 判断弹窗是否已存在,若存在则关闭
                    messageInstance = Message(options)
                }
                // message类型
                const typeArr = ['success', 'error', 'warning', 'info']
                typeArr.forEach(type => {
                    resetMessage[type] = options => {
                        if (typeof options === 'string') options = {
                            message: options
                        }
                        options.type = type
                        return resetMessage(options)
                    }
                })
                resetMessage({
                    showClose: true,
                    message: '您的登录已过期',
                    type: 'error'
                })


            }
            reject(err)
        })
    })
}

export default {
    showApplicationCenterList(params) {
        return fetch('/api/admin/showApplicationCenterList', params,'get')
    },
    addApplicationCenter(params) {
        return fetch('/api/admin/addApplicationCenter', params,)
    },
    delApplicationCenter(params) {
        return fetch('/api/admin/delApplicationCenter', params,'get' )
    },
    editApplicationCenter(params) {
        return fetch('/api/admin/editApplicationCenter', params,)
    },
    queryApplicationCenter(params) {
        return fetch('/api/admin/queryApplicationCenter', params,'get' )
    },
    queryApplicationCenterList(params) {
        return fetch('/api/admin/queryApplicationCenterList', params,'get' )
    },

    searchHome(params) {
        return fetch('/api/content/searchHome', params,)
    },
    /*消息查看*/
    queryNoticeNum(params) {
        return fetch('/api/message/queryNoticeNum', params,'get' )
    },
    queryNotice(params) {
        return fetch('/api/message/queryNotice', params,'get' )
    },
    readNotice(params) {
        return fetch('/api/message/readNotice', params,)
    },

    /*上传图片*/
    myUploadSingle(params) {
        return fetch('/api/admin/myUploadSingle', params, )
    },
    getColumnInfoTreeById(params) {
        return fetch('/api/lanMu/getColumnInfoTreeById', params, 'get')
    },
    /*消息*/
    querySystemSource(params) {
        return fetch('/api/message/querySystemSource', params, 'get')
    },
    queryMessage(params) {
        return fetch('/api/message/queryMessage', params, 'get')
    },
    queryMessageById(params) {
        return fetch('/api/message/queryMessageById', params, 'get')
    },
    queryMessageByWechatId(params) {
        return fetch('/api/message/queryMessageByWechatId', params, 'get')
    },
    receiveMessage(params) {
        return fetch('/api/message/receiveMessage', params, )
    },
    quash(params) {
        return fetch('/api/content/quash', params, )
    },

    //验证码
    getDigitalCaptcha(params) {
        return fetch('api/catpcha/digitalCaptcha', params, 'get')
    },
    getLoginStatus(params) {
        return fetch('api/admin/getLoginStatus', params, 'get')
    },
    //获取当前用户信息
    getUser(params) {
        return fetch('api/admin/getUserInfoByLogin', params, 'get')
    },
    getMenusByLogin(params) {
        return fetch('/api/admin/getMenusByLogin', params, 'get')
    },

    login(params) {
        return fetch('api/system/login', params,)
    },
    getLoginLog(params) {
        return fetch('api/admin/getLoginLog', params,)
    },
    addOrg(params) {
        return fetch('api/admin/addOrg', params,)
    },
    delOrg(params) {
        return fetch('api/admin/delOrg?id=' + params.id, params,)
    },
    editOrg(params) {
        return fetch('api/admin/editOrg', params,)
    },
    getOrgTree(params) {
        return fetch('api/admin/getOrgTree', params, 'get')
    },
    getOrgDetail(params) {
        return fetch('admin/getOrgDetail', params, 'get')
    },
    getRolesTree(params) {
        return fetch('api/admin/getRolesTree', params, 'get')
    },
    addDics(params) {
        return fetch('api/admin/addDics', params,)
    },
    delDics(params) {
        return fetch('api/admin/delDics?id=' + params.id, params,)
    },
    editDics(params) {
        return fetch('api/admin/editDics', params,)
    },
    getDicsByCriteria(params) {
        return fetch('api/admin/getDicsByCriteria', params,)
    },
    getDicDetail(params) {
        return fetch('api/admin/getDicDetail', params,'get')
    },
    getDicTree(params) {
        return fetch('api/admin/getDicTree', params, 'get')
    },
    queryMenusByRoleId(params) {
        return fetch('api/admin/queryMenusByRoleId?roleId=' + params.roleId, params,)
    },
    getRolesByCriteria(params) {
        return fetch('api/admin/getRolesByCriteria', params,)
    },
    delRoles(params) {
        return fetch('api/admin/delRoles', params,)
    },
    addRoles(params) {
        return fetch('api/admin/addRoles', params,)
    },
    editRoles(params) {
        return fetch('api/admin/editRoles', params,)
    },
    submitRoleMenus(params) {
        return fetch('api/admin/submitRoleMenus', params,)
    },
    getUserByCriteria(params) {
        return fetch('api/admin/getUserByCriteria', params,)
    },
    addUser(params) {
        return fetch('api/admin/addUser', params,)
    },
    delUsers(params) {
        return fetch('api/admin/delUsers', params,)
    },
    editUsers(params) {
        return fetch('api/admin/editUsers', params,)
    },
    resetPSW(params) {
        return fetch('api/admin/resetPSW', params,)
    },


    loginSSO(params) {
        return fetch('api/system/loginSSO', params,)
    },
    //api接口文档

    addSystem(params) {
        return fetch('api/ApiSystem/add', params,)
    },
    getApiSystemList(params) {
        return fetch('api/ApiSystem/paginQuery', params,)
    },
    editApiSystem(params) {
        return fetch('api/ApiSystem/edit', params,'put')
    },
    publishApiSystem(params) {
        return fetch('api/ApiSystem/publishApiSystem', params,'get')
    },
    closeApiSystem(params) {
        return fetch('api/ApiSystem/closeApiSystem', params,'get')
    },
    addApiMethod(params) {
        return fetch('api/ApiSystem/addMethod', params,)
    },
    getApiMethodList(params) {
        return fetch('api/ApiSystem/paginMethodQuery', params,)
    },
    publishMethod(params) {
        return fetch('api/ApiSystem/publishMethod', params,'get')
    },
    closeMethod(params) {
        return fetch('api/ApiSystem/closeMethod', params,'get')
    },
    editMethod(params) {
        return fetch('api/ApiSystem/editMethod', params,'put')
    },
    getApiApplyList(params) {
        return fetch('api/ApiApplication/innerPaginQuery', params,)
    },
    dealApplication(params) {
        return fetch('api/ApiApplication/dealApplication', params,)
    },
    dealApplyApiService(params) {
        return fetch('api/ApiApplication/dealApplyApiService', params,)
    },
    closeSecret(params) {
        return fetch('api/ApiApplication/closeSecret', params,'get')
    },
    openSecret(params) {
        return fetch('api/ApiApplication/openSecret', params,'get')
    },

    /*首页接口*/
    newQuery(params) {
        return fetch('api/homepage/newQuery', params,)
    },
    announcementQuery(params) {
        return fetch('api/homepage/announcementQuery', params,)
    },
    messageQuery(params) {
        return fetch('api/homepage/messageQuery', params,)
    },
    queryDoneMessage(params) {
        return fetch('api/homepage/queryDoneMessage', params,)
    },
    queryUndoneMessage(params) {
        return fetch('api/homepage/queryUndoneMessage', params,)
    },
    queryMessageNum(params) {
        return fetch('api/homepage/queryMessageNum', params,'get')
    },
    paginHome(params) {
        return fetch('api/content/paginHome', params,)
    },

/*内容管理对象功能接口*/
    getContentLogs(params) {
        return fetch('/api/content/getContentLogs?contentId='+params.contentId, '', )
    },
    contentAdd(params) {
        return fetch('/api/content/add', params,)
    },
    contentAudit(params) {
        return fetch('api/content/audit', params,)
    },
    contentDelete(params) {
        return fetch('/api/content/delete?id='+params.id, '',)
    },
    contentDeleteBatch(params) {
        return fetch('/api/content/deleteBatch', params,)
    },
    contentEdit(params) {
        return fetch('/api/content/edit', params,'put')
    },
    contentPaginQuery(params) {
        return fetch('/api/content/paginQuery', params,)
    },
    getContentById(params) {
        return fetch('/api/content/detail', params,'get')
    },
    //栏目管理
    addColumnInfo(params) {
        return fetch('/api/lanMu/addColumnInfo', params,)
    },
    getColumnInfoList(params) {
        return fetch('/api/lanMu/getColumnInfoList', params,)
    },
    updateColumnInfo(params) {
        return fetch('/api/lanMu/updateColumnInfo', params,)
    },
    deleteColumnInfo(params) {
        return fetch('/api/lanMu/deleteColumnInfo', params,'get')
    },
    getColumnInfoTitle(params) {
        return fetch('/api/lanMu/getColumnInfoTitle', params,'get')
    },
    getColumnInfoTree(params) {
        return fetch('/api/lanMu/getColumnInfoTree', params,'get')
    },
    updateColumnInfoNavigation(params) {
        return fetch('/api/lanMu/updateColumnInfoNavigation', params,'get')
    },
    getUserForReviewer(params) {
        return fetch('/api/lanMu/getUserForReviewer', params,'get')
    },
    updateColumnReviewer(params) {
        return fetch('/api/lanMu/updateColumnReviewer', params,'post')
    },
    paginAuditQuery(params) {
        return fetch('/api/content/paginAuditQuery', params,'post')
    },
}
